<template>
  <div class="correlationView bi-ui-dialog-content"
       style="padding-top: 0px !important;">
    <div class="descriptionLine">{{ dialogTitle }}</div>
    <div class="correlationTopView">
      <div class="topViewLeft">

        <div class="typeSelectorBox" @click.stop="pover = !pover">
          <el-input :placeholder="this.typeSelectorBoxInputValue" :style="sliderStyle" readonly>
            <i v-show="pover === false" slot="suffix" class="el-icon-arrow-down" style="margin: 9px 0px 0px 6px;"></i>
            <i v-show="pover === true" slot="suffix" class="el-icon-arrow-up" style="margin: 9px 0px 0px 6px;"></i>
          </el-input>
        </div>
        <div class="typeList pover" v-show="pover" @click="closeMsg" ref="pover">
          <div class="filter-toobar" style="border: none">
            <div
                class="check-all checkallitem"
                style="height: 23px;width:827px !important;background-color: white;border-bottom: none">
              <el-checkbox
                  :indeterminate="isIndeterminate"
                  v-model="checkAll"
                  @change="handleCheckAllChange">
                全选
              </el-checkbox>
            </div>
            <div class="sub-check-group subchecks">
              <div v-for="(groupItem,group) in subTypes" :key="group">
                <el-checkbox class="group-checkbox"
                             :indeterminate="groupItem.indeminate"
                             v-model="groupItem.checked"
                             @change="handleCheckSubAllChange($event,group)"
                             :label="group"
                             :key="group"
                             style="margin-right: 16px;">
                  {{ group }}
                </el-checkbox>
                <el-checkbox-group v-model="checkedTypes[group]" @change="handleCheckedTypesChange($event,group)">
                  <el-checkbox v-for="entityType in entityTypes[group]" :label="entityType" :key="entityType"
                               class="mintypes">{{ entityType }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </div>

        <div class="entitySearch">
          <el-input v-model="searchText" class="bi-el-search-realtime bi-el-search-transfer"
                    style="width: 200px;height: 32px;" placeholder="输入搜索实体标题" @input="doEntitySearch" clearable>
            <i slot="prefix" class="el-icon-search" style="margin: 10px 0px 0px 6px;"></i>
          </el-input>
        </div>

        <div class="relationSelector">
          <el-radio-group v-model="selectValue" @change="selectValueFunc">
            <el-radio size="mini" label="in">血缘分析</el-radio>
            <el-radio size="mini" label="out">影响分析</el-radio>
          </el-radio-group>
        </div>
      </div>

      <div>
        <a class='bi-el-btn bi-el-btn-link' style="height: 48px !important;margin-right: 8px" @click="tableExportFunc"
           download="">导出</a>
      </div>
    </div>
    <!--页面中部-->
    <div class="correlationMiddleView">
      <vxe-table
          v-loading="loading"
          :data="tableData"
          border
          resizable
          height="100%"
          class="bi-vxe-table">
        <vxe-table-column
            field="title"
            title="标题"
            fixed
            width="130"
            show-overflow="tooltip">
          <template slot-scope="scope">
                <span
                    v-html="scope.row.title"
                    class="bi-el-btn-text"
                    type="text"
                    @click="checkTheDetailLeft(scope.row)"
                    style="color: #09446D">
                </span>
          </template>
        </vxe-table-column>
        <vxe-table-column
            field="name"
            title="标识"
            width="130"
            show-overflow="tooltip">
        </vxe-table-column>
        <vxe-table-column
            field="type"
            title="类型"
            width="100"
            show-overflow="tooltip">
        </vxe-table-column>
        <vxe-table-column
            field="path"
            title="路径"
            width="300"
            show-overflow="tooltip">
        </vxe-table-column>
        <vxe-table-column
            title="关联关系路径"
            width="auto"
            show-overflow="tooltip">
          <template slot-scope="scope">
            <div class="theRowFive">
              <div v-for="(pathItem,pathKey) in scope.row.entityBeanPath" :key="pathKey">
                <div v-if="pathKey === scope.row.entityBeanPath.length-1">
                  <el-button class="bi-el-btn-text" type="text" @click="checkTheDetail(pathItem)">{{ pathItem.title }}
                  </el-button>
                </div>
                <div v-else-if="pathKey !== scope.row.entityBeanPath.length-1">
                  <el-button class="bi-el-btn-text" type="text" @click="checkTheDetail(pathItem)">{{ pathItem.title }}
                  </el-button>
                  <span class="icon bi-ui-iconfont bi-ui-icon-right-arrow"></span>
                </div>
              </div>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>
    <!--页面下部，关于分页组件-->
    <div class="correlationBottomView">
      <el-pagination
          class="bi-el-pagination"
          popper-class="bi-el-page-content"
          style="padding-right: 6px"
          layout="total, prev, pager, next, jumper, sizes, slot"
          :current-page="currentPage"
          :page-sizes="sizelist"
          :page-size="pageSize"
          :total="totalPathSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import request from '../../utils/request'
import { Debounce } from '../../utils/debounce'
import qs from 'qs'

export default {
  name: 'correlationView',
  data () {
    return {
      pover: false,
      loading: true,
      totalPathSize: 0,
      currentPage: 1,
      pageSize: 10,
      nodeGuid: this.$route.query.guid,
      nodeTitle: this.$route.query.title,
      dialogTitle: '',
      isIndeterminate: false,
      checkAll: true,
      subTypes: {
        '菜单': { indeminate: false, checked: true },
        '数据建模': { indeminate: false, checked: true },
        '数据分析': { indeminate: false, checked: true },
        '数据可视化': { indeminate: false, checked: true },
        '信息资源': { indeminate: false, checked: true },
        '数据稽核': { indeminate: false, checked: true }
      },
      checkedTypes: {
        '菜单': ['菜单项', '导航树', '导航树节点'],
        '数据建模': ['业务视图二维表', '维度', 'Cube', '指标', '公共参数', '私有参数'],
        '数据分析': ['SQL数据集', '查询数据集', 'Cube数据集', '指标数据集', 'Excel数据集'],
        '数据可视化': ['仪表盘', '图表', '文字板块', '分析表', '即席查询模板'],
        '信息资源': ['接入点', '标准代码', '代码映射', '数据资源', '信息资源'],
        '数据稽核': ['稽核规则', '稽核模型']
      },
      entityTypes: {
        '菜单': ['菜单项', '导航树', '导航树节点'],
        '数据建模': ['业务视图二维表', '维度', 'Cube', '指标', '公共参数', '私有参数'],
        '数据分析': ['SQL数据集', '查询数据集', 'Cube数据集', '指标数据集', 'Excel数据集'],
        '数据可视化': ['仪表盘', '图表', '文字板块', '分析表', '即席查询模板'],
        '信息资源': ['接入点', '标准代码', '代码映射', '数据资源', '信息资源'],
        '数据稽核': ['稽核规则', '稽核模型']
      },
      tableData: [],
      selectValue: 'out',
      searchText: '',
      typeSelectorBoxInputValue: '已选择 0 项实体类型',
      sliderStyle: {
        width: '390px'
      },
      sizelist: [10, 20, 30, 40]
    }
  },
  beforeCreate () {
    document.querySelector('body').setAttribute('style', 'overflow:auto;')
  },
  create () {

  },
  mounted () {
    this.setDialogName()
    this.correlationSearch()
    this.typeEcho()
    document.addEventListener('click', this.closeMsg)
  },
  // 实现 点击空白处 隐藏类型列表
  destroyed () {
    document.addEventListener('click', this.closeMsg)
  },
  methods: {

    // 前端调用后端的接口函数（相关性查询）
    searchCorrelation: function (datas) {
      return request.post('/metagraph/correlation', qs.stringify(datas))
    },

    // 前端调用后端的接口函数（表格导出）
    exportCorrelation: function (datas) {
      return request.post('/metagraph/correlation/export', qs.stringify(datas), {
        headers: { 'Content-Type': 'application/octet-stream' },
        responseType: 'blob'
      })
    },

    // 前端调用后端的接口函数（详细信息查询）
    getDetailViewUrl: function (datas) {
      return request.get('/metagraph/viewurl', { params: datas })
    },

    // 动态生成对话框标题、准备导出的表格标题
    setDialogName () {
      // eslint-disable-next-line no-unused-vars
      this.dialogTitle = this.nodeTitle
      this.dialogTitle += '的相关性查询'
    },
    // 点击全选
    handleCheckAllChange: Debounce(function (val) {
      if (val) {
        this.checkedTypes = _.cloneDeep(this.entityTypes)
        this.subTypes = {
          '菜单': { indeminate: false, checked: true },
          '数据建模': { indeminate: false, checked: true },
          '数据分析': { indeminate: false, checked: true },
          '数据可视化': { indeminate: false, checked: true },
          '信息资源': { indeminate: false, checked: true },
          '数据稽核': { indeminate: false, checked: true }
        }

        // 回显已选择类型
        this.typeEcho()

        this.currentPage = 1
        this.correlationSearch()
      } else {
        this.checkedTypes = {
          '菜单': [],
          '数据建模': [],
          '数据分析': [],
          '数据可视化': [],
          '信息资源': [],
          '数据稽核': []
        }

        this.subTypes = {
          '菜单': { indeminate: false, checked: false },
          '数据建模': { indeminate: false, checked: false },
          '数据分析': { indeminate: false, checked: false },
          '数据可视化': { indeminate: false, checked: false },
          '信息资源': { indeminate: false, checked: false },
          '数据稽核': { indeminate: false, checked: false }
        }

        this.typeSelectorBoxInputValue = '已选择 0 项实体类型'
      }
      this.isIndeterminate = false

      this.currentPage = 1
      this.correlationSearch()
    }, 1000),

    // 点击二级菜单（部分全选）
    handleCheckSubAllChange (val, group) {
      this.checkedTypes[group] = val ? this.entityTypes[group] : []
      this.handleCheckedTypesChange(this.checkedTypes[group], group)
      this.subTypes[group].indeminate = false
      this.typeEcho()
    },

    // 点击某个具体的实体类型
    handleCheckedTypesChange: Debounce(function (value, group) {
      let checkedCount = value.length
      this.subTypes[group].checked = checkedCount === this.entityTypes[group].length
      this.subTypes[group].indeminate = checkedCount > 0 && checkedCount < this.entityTypes[group].length

      let checkedAll = true
      for (const type in this.subTypes) {
        checkedAll = checkedAll && this.subTypes[type].checked
      }
      this.checkAll = checkedAll
      let typesArr = []
      for (const checkedType in this.checkedTypes) {
        let types = this.checkedTypes[checkedType]
        typesArr = typesArr.concat(types)
      }
      this.isIndeterminate = typesArr.length > 0 && !checkedAll

      this.typeEcho()
      this.currentPage = 1
      this.correlationSearch()
    }, 1000),

    // 选择某一关联关系类型后进行调用
    selectValueFunc () {
      this.currentPage = 1
      this.correlationSearch()
    },

    // 输入框中回显已选择类型,输入框宽度自适应
    typeEcho () {
      if (this.checkAll) {
        this.typeSelectorBoxInputValue = '已选择全部实体类型'
      } else {
        let num = 0
        // 遍历已经选择的类型数组，
        for (const checkedType in this.checkedTypes) {
          let types = this.checkedTypes[checkedType]
          num += types.length
        }
        this.typeSelectorBoxInputValue = '已选择: ' + num + ' 项实体类型'
      }
    },

    // 装配相关性查询信息
    correlationSearch () {
      // 当开始搜索时，加载遮罩层开始显示
      this.loading = true
      // 当开始搜索时，实体类型悬浮框进行隐藏
      this.pover = false
      let typesArr = []
      for (const checkedType in this.checkedTypes) {
        let types = this.checkedTypes[checkedType]
        typesArr = typesArr.concat(types)
      }

      // get方式传参数，前端需要编码，后端需要解码
      let datas = {
        keyword: this.nodeGuid,
        types: typesArr.length > 0 ? encodeURIComponent(JSON.stringify(typesArr)) : '',
        relationString: this.selectValue,
        filterString: this.searchText,
        pageSize: this.pageSize,
        currentPage: this.currentPage
      }

      this.searchCorrelation(datas).then(res => {
        this.totalPathSize = res.totalSize ? res.totalSize : 0
        this.tableData = res.correlationTableBeans
        this.loading = false
      })
    },

    // 输入框，输入准备在所示列表中查找的实体对象名称
    doEntitySearch: Debounce(function () {
      this.currentPage = 1
      this.correlationSearch()
    }, 1000),
    // 标题行支持超链接
    checkTheDetailLeft (titleItem) {
      let item = {
        type: titleItem.preType,
        guid: titleItem.guid
      }
      this.checkTheDetail(item)
    },
    // 以实体为基本单位组成的相关性路径中，点击具体某一节点可以查看其详细信息
    checkTheDetail (pathItem) {
      this.getDetailViewUrl({ type: pathItem.type, guid: pathItem.guid }).then(res => {
        if (!res.success) {
          window.VueBI.Dialog.warn('该类型图谱节点不支持查看详情！')
          return
        }
        let resourceUrl = res.viewUrl
        let basePath = this.$frontContextPath.replaceAll('/output/@bi', '')
        if (basePath.charAt(basePath.length - 1) === '/') {
          basePath = basePath.substr(0, basePath.length - 1)
        }
        let iframeUrl = basePath + (resourceUrl.charAt(0) === '/' ? resourceUrl : ('/' + resourceUrl))
        window.$.bi.getRootWindow().nros.getPlugin('event').emit('open-page', { appName: 'metagraph-app', iframeUrl: iframeUrl })
      })
    },

    // 以excel的形式导出全部相关性信息
    tableExportFunc () {
      let typesArr = []
      for (const checkedType in this.checkedTypes) {
        let types = this.checkedTypes[checkedType]
        typesArr = typesArr.concat(types)
      }
      let datas = {
        keyword: this.nodeGuid,
        types: typesArr.length > 0 ? encodeURIComponent(JSON.stringify(typesArr)) : '',
        relationString: this.selectValue,
        filterString: this.searchText,
        excelName: this.dialogTitle,
        pageSize: this.pageSize,
        currentPage: this.currentPage
      }

      this.exportCorrelation(datas).then(res => {
        const blob = new Blob([res], { type: 'application/octet-stream' })
        const url = window.URL.createObjectURL(blob)
        const aLink = document.createElement('a')
        aLink.style.display = 'none'
        aLink.href = url
        aLink.setAttribute('download', this.dialogTitle + '.xls')
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
      }).catch(() => {
        window.VueBI.Dialog.error('导出失败')
      })
    },

    // 处理当前页信息
    handleCurrentChange (val) {
      this.tableData = []
      this.currentPage = val
      this.correlationSearch()
    },

    // 处理页容量信息
    handleSizeChange (val) {
      this.tableData = []
      this.pageSize = val
      this.currentPage = 1
      this.correlationSearch()
    },
    // 实现 点击空白处 隐藏类型列表
    closeMsg (e) {
      let self = this
      if (self.pover === true && !this.$refs.pover.contains(e.target)) {
        self.pover = false
      }
    }

  }

}
</script>

<style lang="scss" scoped>
.descriptionLine {
  width: auto;
  height: 55px;
  line-height: 55px;
  text-align: left;
  font-size: 15px;
  padding-left: 10px;
}

.correlationView {
  min-width: 1240px;
  height: 99%;
  display: flex;
  flex-direction: column;
  justify-content: left;
}

.correlationTopView {
  //border: 1px red solid;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: auto;
  height: 48px;
}

.topViewLeft {
  width: auto;
  display: flex;
  flex-direction: row;
  justify-content: left;
  //border: 1px red solid;
}

.typeSelectorBox {
  margin-left: 10px;
}

.typeSelectorBox /deep/ input::-webkit-input-placeholder {
  color: #282c34;
  font-size: 15px;
}

.typeList {
  position: absolute;
  left: 34px;
  top: 90px;
  width: 845px;
  height: 180px;
  border: 2px #b3d8ff solid;
  background-color: #ffffff;
  z-index: 99;
}

.subchecks {
  height: auto;
  display: flex;
  flex-direction: row;
  justify-content: left;
  align-content: center;
}

.relationSelector {
  margin-left: 30px;
  height: 30px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-top: 3px;
}

.entitySearch {
  margin-left: 10px;
}

.entitySearch ::v-deep {
  .bi-el-search-transfer .el-input__inner {
    height: 32px;
  }
}

.correlationMiddleView {
  //border: 1px red solid;
  width: 98.7%;
  height: 99%;
  margin: 8px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.middleView-top {
  width: 100%;
  height: 36px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.theRowFive {
  display: flex;
  flex-direction: row;
  justify-content: left;
  align-items: center;
}

.correlationBottomView {
  //border: 1px red solid;
  width: 100%;
  height: 35px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
}

</style>
